package com.zjj.algorithm.learning.atguigu.stack;

/**
 * @author zjj_admin
 * @date 2022/11/8 21:58
 */
public class LinkedListStackDemo {

    public static void main(String[] args) {

        LinkedListStack listStack = new LinkedListStack(3);
        listStack.push(1);
        listStack.push(2);
        listStack.push(3);
        listStack.push(4);

        listStack.show();

        listStack.pop();
        listStack.pop();
        System.out.println("=============");
        listStack.show();

    }
}


/**
 * 定义一个栈
 */
class LinkedListStack{

    /**
     * 栈的最大容量
     */
    private int maxSize;
    /**
     * 栈中元素个数
     */
    private int nodeNum = 0;
    /**
     * 头结点，不存储数据
     */
    private Node head;
    /**
     * 栈顶元素
     */
    private Node top ;

    public LinkedListStack(int maxSize) {
        this.top = new Node();
        this.head = new Node();
        this.head.setNext(this.top);
        this.maxSize = maxSize;
    }

    public boolean isEmpty(){
        return this.nodeNum <= 0;
    }
    public boolean isFull(){
        return this.maxSize <= this.nodeNum;
    }

    public void push(int data){
        if (isFull()) {
            System.out.println("栈已经满了，不能够添加了");
            return;
        }
        Node node = new Node(data);
        node.setNext(this.head.getNext());
        this.head.setNext(node);
        this.top = node;
        this.nodeNum ++;
    }

    public int pop(){
        if (isEmpty()) {
            throw new RuntimeException("栈中没有数据");
        }
        Node node = this.top;
        this.head.setNext(this.head.getNext().getNext());
        this.top = this.head.getNext();
        this.nodeNum --;
        return node.getVal();
    }

    public void show(){
        if (isEmpty()) {
            System.out.println("栈中没有数据");
            return;
        }
        Node curr = this.top;
        while (true){
            if(curr.getNext() == null){
                break;
            }
            System.out.println("栈中的数据为：" + curr.getVal());
            curr = curr.getNext();

        }

    }
}


class Node{
    private int val;
    private Node next;

    public Node() {
    }

    public Node(int val) {
        this.val = val;
    }

    public int getVal() {
        return val;
    }

    public void setVal(int val) {
        this.val = val;
    }

    public Node getNext() {
        return next;
    }

    public void setNext(Node next) {
        this.next = next;
    }
}
